#!/bin/sh

if [ $# -lt 1 ]
then
	echo "usage: $0 'srm-path' [pattern1] [pattern2]";
	exit 1;
fi

if [ -n $2 ]
then
pattern1=$2
fi

if [ -n $3 ]
then
pattern2=$3
fi

curdir=`pwd`;

findfiles()
{

	local path=`lcg-ls $1 |  sed -e  's/\(.*\)\/\(.*\)/\2/'` 
#	echo "path: $path"


	for name in ${path[@]}
		do
			local file=`echo $name |  awk "{if (match(\\$0,\".\")&&match(\\$0,\"$pattern1\")&&match(\\$0,\"$pattern2\") ) print \\$0 }"`
#			echo "file: $file"
			if [ -n "$file"  ]
			then
				echo "lcg-cp \"$1/$name\" \"file:///$curdir/$name\"";
			else
				findfiles "$1/$name/";
			fi
		done


}

copyfiles()
{
	local path=`lcg-ls $1 |  sed -e  's/\(.*\)\/\(.*\)/\2/'`
	for name in ${path[@]}
		do
			local file=`echo $name |  awk "{if (match(\\$0,\".\")&&match(\\$0,\"$pattern1\")&&match(\\$0,\"$pattern2\") ) print \\$0 }"`
			if [ -n "$file"  ]
			then
				echo "lcg-cp -v \"$1/$name\" \"file:///$curdir/$name\"" | sh;
			else
				copyfiles "$1/$name/";
			fi
		done


}



findfiles $1;
#a=`findfiles $1`;
#echo "$a";



echo -n "Are you ready to copy the files above? [y/n] ";
read x

if [ "$x"  = 'y' ]
then
	copyfiles $1
#	echo "$a" | sh;
fi
